package com.xs.mcpserver.config;

import com.xs.mcpserver.gitlab.GitLabConfig;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gitlab4j.api.GitLabApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

@Slf4j
@Component
@RequiredArgsConstructor
public class GitLabApiHolder {
    @Getter
    private static GitLabApi gitLabApi;

    private final GitLabConfig gitLabConfig;

    @PostConstruct
    public void init() {
        if (gitLabApi == null) {
            synchronized (GitLabApiHolder.class) {
                if (gitLabApi == null) {
                    try {
                        // 创建信任所有证书的SSLContext
                        SSLContext sslContext = SSLContext.getInstance("TLS");
                        TrustManager[] trustAllCerts = new TrustManager[]{
                            new X509TrustManager() {
                                @Override
                                public X509Certificate[] getAcceptedIssuers() {
                                    return new X509Certificate[0];
                                }
                                @Override
                                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                                }
                                @Override
                                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                                }
                            }
                        };
                        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

                        // 创建GitLabApi实例并配置忽略证书验证
                        gitLabApi = new GitLabApi(gitLabConfig.getUrl(), gitLabConfig.getToken());
                        gitLabApi.setIgnoreCertificateErrors(true);
                        
                        log.warn("警告: GitLab API已配置为忽略SSL证书验证。这种配置不建议在生产环境中使用。");
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        throw new RuntimeException("初始化SSL配置失败", e);
                    }
                }
            }
        }
    }
}
